package Servlet;

import Bean.Register;
import Bean.User;
import Service.RegisterService;
import Utils.UUIDUtils;
import Utils.UploadFileUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张
 * Date: 2025-03-09
 * Time: 12:33
 */
@WebServlet("/UserRegisterServlet")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024,  // 1MB
        maxFileSize = 1024 * 1024 * 5,    // 5MB
        maxRequestSize = 1024 * 1024 * 10 // 10MB
)
public class UserRegisterServlet extends HttpServlet {
    public RegisterService registerService = new RegisterService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        User user = new User();
        user.setUserId(UUIDUtils.getId());
        user.setName(req.getParameter("userName"));
        user.setPhone(req.getParameter("phone"));
        user.setPassword(req.getParameter("password"));
        user.setIdentityCard(req.getParameter("idCard"));

        //处理头像
        Part filePart = req.getPart("avatar");
        UploadFileUtil uploadUtil = new UploadFileUtil();

        //设置保存路径
        String uploadPath = "D:\\upload\\avatars";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs(); // 创建多级目录
        }

        uploadUtil.setPath(uploadPath);
        uploadUtil.setPart(filePart);
        String originalFilename = uploadUtil.getFilename();
        user.setUimage("/avatars/" + originalFilename);
        boolean ok = false;
        //提交注册申请
        if(uploadUtil.saveFile(originalFilename) == 1) {
            ok = registerService.register(user);
        }
        if(ok) {
            req.setAttribute("status", "success");
            req.setAttribute("message", "注册申请已提交!");
            req.setAttribute("redirectUrl", "login.jsp");
            req.setAttribute("waitSeconds", 3);
        } else {
            req.setAttribute("status", "error");
            req.setAttribute("message", "申请失败,请重新尝试");
            req.setAttribute("redirectUrl", "user_register.jsp");
            req.setAttribute("waitSeconds", 2);
            req.getRequestDispatcher("skip.jsp").forward(req,resp);
        }

        req.getRequestDispatcher("skip.jsp").forward(req,resp);
    }
}
